package com.kelvin.backend.common.web.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kelvin.backend.common.web.dao.BaseDao;
import com.kelvin.backend.common.web.entity.BaseEntity;
import com.kelvin.backend.common.web.entity.page.PageEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>Title: BaseService</p>
 * <p>Description: </p>
 *
 * @author Kelvin.Chen
 * @datetime 2021/7/9 14:30
 */
public abstract class BaseService<D extends BaseDao<T>, T extends BaseEntity> implements IBaseService<T> {

    protected Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    protected D baseDao;

    public BaseService() {
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public boolean saveOrUpdate(T entity) {
        if (null == entity) {
            return false;
        }
        if (ObjectUtil.isNotEmpty(entity.getId())) {
            T exists = selectById(entity.getId());
            if (null != exists) {
                return update(entity);
            } else {
                return save(entity);
            }
        } else {
            return save(entity);
        }
    }

    @Override
    public List<T> selectByWrapper(Wrapper<T> queryWrapper, ServiceHandle<T> serviceHandle) {
        return null;
    }


    @Override
    public Page<T> selectPage(PageEntity pageEntity, Wrapper<T> queryWrapper) {
        Page page = pageEntity.initPage();
        return this.baseDao.selectPage(page, queryWrapper);
    }

    @Override
    public Page<T> selectPage(PageEntity pageEntity) {
        return this.selectPage(pageEntity, Wrappers.emptyWrapper());
    }

    @Override
    public Page<T> selectPage(PageEntity pageEntity, Wrapper<T> queryWrapper, ServiceHandle<T> serviceHandle) {
        Page<T> page = this.selectPage(pageEntity, queryWrapper);
        if (null != serviceHandle) {
            List<T> list = page.getRecords();
            page.setRecords(serviceHandle.handle(list));
        }
        return page;
    }
}
